package top.lywivan.mm.filter;

import top.lywivan.mm.common.GlobalConst;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        if(uri.contains("/login.html")||uri.contains("/login")||uri.contains("css/style.css")||uri.contains("css/element-ui.css")
                ||uri.contains("js/vue.js")||uri.contains("js/element-ui.js")||uri.contains("plugins/jquery/dist/jquery.js")
                ||uri.contains("js/axios-0.18.0.js")||uri.contains("js/base.js")
                ||uri.contains("/plugins/"))
            filterChain.doFilter(servletRequest, servletResponse);
        else {
            HttpSession session = request.getSession();
            Object user = session.getAttribute(GlobalConst.SESSION_KEY_USER);
            if(user!=null){
                filterChain.doFilter(servletRequest, servletResponse);
            }
            else {
                HttpServletResponse resp = (HttpServletResponse) servletResponse;
                resp.sendRedirect("/mm/login.html");
            }
        }
    }
}
